//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v2"
)

type MongoCfg struct {
	Url      string `yaml:"url"`
	DataBase string `yaml:"dataBase"`
}

type RedisCfg struct {
	Addr     string `yaml:"addr"`
	PassWord string `yaml:"passWord"`
}

type ExtensionServerCfg struct {
	RemoteAddr string `yaml:"remoteAddr"`
}

type AtomGitCfg struct {
	ClientId     string `yaml:"clientId"`
	ClientSecret string `yaml:"clientSecret"`
}

type GiteeCfg struct {
	ClientId     string `yaml:"clientId"`
	ClientSecret string `yaml:"clientSecret"`
}

type JihulabCfg struct {
	ClientId     string `yaml:"clientId"`
	ClientSecret string `yaml:"clientSecret"`
}

type GitCodeCfg struct {
	ClientId     string `yaml:"clientId"`
	ClientSecret string `yaml:"clientSecret"`
}

type DataBaseCfg struct {
	Mongo     MongoCfg           `yaml:"mongo"`
	FileStore ExtensionServerCfg `yaml:"fileStore"`
	Redis     RedisCfg           `yaml:"redis"`
}

type ClientCfg struct {
	ServerAddr   string `yaml:"serverAddr"`
	DisableLogin bool   `yaml:"disableLogin"`
}

type LoggingCfg struct {
	Grpc    string `yaml:"grpc"`
	Task    string `yaml:"task"`
	Webhook string `yaml:"webhook"`
	Error   string `yaml:"error"`
}

type AdminCfg struct {
	Enable      bool   `yaml:"enable"`
	SuperUser   string `yaml:"superUser"`
	SuperPubKey string `yaml:"superPubKey"`
}

type ServerConfig struct {
	GrpcPort     uint16      `yaml:"grpcPort"`
	HttpPort     uint16      `yaml:"httpPort"`
	MetricPort   uint16      `yaml:"metricPort"`
	WebAddr      string      `yaml:"webAddr"`
	TraceAddr    string      `yaml:"traceAddr"`
	GlobalServer bool        `yaml:"globalServer"`
	Logging      LoggingCfg  `yaml:"logging"`
	AtomGit      AtomGitCfg  `yaml:"atomGit"`
	Gitee        GiteeCfg    `yaml:"gitee"`
	Jihulab      JihulabCfg  `yaml:"jihulab"`
	GitCode      GitCodeCfg  `yaml:"gitCode"`
	DataBase     DataBaseCfg `yaml:"dataBase"`
	ClientCfg    ClientCfg   `yaml:"clientCfg"`
	Admin        AdminCfg    `yaml:"admin"`
}

func ReadConfig(fileName string) (*ServerConfig, error) {
	data, err := os.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	servCfg := &ServerConfig{}
	err = yaml.Unmarshal(data, servCfg)
	if err != nil {
		return nil, err
	}
	if servCfg.GrpcPort == 0 {
		return nil, fmt.Errorf("miss grpcPort")
	}
	if servCfg.HttpPort == 0 {
		return nil, fmt.Errorf("miss httpPort")
	}
	if servCfg.MetricPort == 0 {
		return nil, fmt.Errorf("miss metricPort")
	}
	return servCfg, nil
}
